package bingosoft.metro.datasync.uuap.client.service;

import bingosoft.components.base.service.BaseService;
import bingosoft.components.base.service.Result;
import bingosoft.components.base.service.ResultEntity;
import bingosoft.metro.datasync.uuap.client.form.*;
import bingosoft.metro.datasync.uuap.client.helper.DateHelper;
import bingosoft.metro.datasync.uuap.client.param.RequestParam;
import com.alibaba.fastjson.JSONObject;
import leap.lang.Strings;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author feily
 * @功能描述  数据业务客户端服务类
 * @创建时间 2018-07-31 20:03:10
 */
public class DataClientService extends BaseService{

	public static final String MESSAGE_PARAM_APP_TOKEN_NULL = "参数【appToken】不能为空";

	/**
	 * 服务请求路径
	 */
	protected String serverPath;

	/**
	 * 应用身份标识
	 */
	protected String appToken;


	/**
	 * 构建函数
	 */
	public DataClientService() {
		this.setLogClass(this.getClass());
	}

	/**
	 * 全量获取应用菜单列表
	 * @return 获取结果
	 */
	public ResultEntity<List<MenuDataForm>> queryMenus() {
		this.logMethodCalled("queryMenus");

		ResultEntity<List<MenuDataForm>> resultEntity = new ResultEntity<List<MenuDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<MenuDataForm> menus = new ArrayList<MenuDataForm>();
			
			String url = this.buildUrl("queryMenus");
			ResultEntity<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}
			
			// update by feily 20190323 修改json转换类库 begin
			/* 
			MenuDataForm[] arrayMenus = JSON.decodeArray(resultContent.getBusinessObject(), MenuDataForm.class);
			for (int i = 0; i < arrayMenus.length; i++) {
				menus.add(arrayMenus[i]);
			}
			*/
			
			String businessObject = resultContent.getBusinessObject();
			List<MenuDataForm> arrayMenus = JSONObject.parseArray(businessObject, MenuDataForm.class);

			for(MenuDataForm menuDataForm:arrayMenus){
				menus.add(menuDataForm);
			}
			// update by feily 20190323 修改json转换类库 end

			resultEntity.setBusinessObject(menus);

		} catch (Exception ex) {
			this.logError("获取菜单信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * 增量获取组织信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public ResultEntity<List<OrgDataForm>> queryOrgs(RequestParam requestParam) {
		this.logMethodCalled("queryOrgs");
		this.logParamValue("requestParam", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		ResultEntity<List<OrgDataForm>> resultEntity = new ResultEntity<List<OrgDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<OrgDataForm> orgs = new ArrayList<OrgDataForm>();
			
			String url = this.buildUrl("queryOrgs", updateBeginDate, updateEndDate);
			ResultEntity<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}

			// update by feily 20190323 修改json转换类库 begin
			/* 
			OrgDataForm[] arrayMenus = JSON.decodeArray(resultContent.getBusinessObject(), OrgDataForm.class);
			for (int i = 0; i < arrayMenus.length; i++) {
				orgs.add(arrayMenus[i]);
			}
			*/
			
			String businessObject = resultContent.getBusinessObject();
			List<OrgDataForm> arrayMenus = JSONObject.parseArray(businessObject, OrgDataForm.class);
			for(OrgDataForm orgDataForm:arrayMenus){
				orgs.add(orgDataForm);
			}
			// update by feily 20190323 修改json转换类库 end

			resultEntity.setBusinessObject(orgs);

		} catch (Exception ex) {
			this.logError("获取组织信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * 增量获取用户信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public ResultEntity<List<UserDataForm>> queryUsers(RequestParam requestParam) {
		this.logMethodCalled("queryUsers");
		this.logParamValue("requestParam", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		ResultEntity<List<UserDataForm>> resultEntity = new ResultEntity<List<UserDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<UserDataForm> users = new ArrayList<UserDataForm>();

			String url = this.buildUrl("queryUsers", updateBeginDate, updateEndDate);
			ResultEntity<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}
			
			// update by feily 20190323 修改json转换类库 begin
			/* 
			UserDataForm[] arrayMenus = JSON.decodeArray(resultContent.getBusinessObject(), UserDataForm.class);
			for (int i = 0; i < arrayMenus.length; i++) {
				users.add(arrayMenus[i]);
			}
			*/
			
			String businessObject = resultContent.getBusinessObject();
			List<UserDataForm> arrayMenus = JSONObject.parseArray(businessObject, UserDataForm.class);

			for(UserDataForm userDataForm:arrayMenus){
				users.add(userDataForm);
			}
			// update by feily 20190323 修改json转换类库 end
			
			resultEntity.setBusinessObject(users);

		} catch (Exception ex) {
			this.logError("获取用户信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * 增量获取权限信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public ResultEntity<List<PermissionDataForm>> queryPermissions(RequestParam requestParam) {
		this.logMethodCalled("queryPermissions");
		this.logParamValue("requestParam", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		ResultEntity<List<PermissionDataForm>> resultEntity = new ResultEntity<List<PermissionDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {

			List<PermissionDataForm> permissions = new ArrayList<PermissionDataForm>();

			String url = this.buildUrl("queryPermissions", updateBeginDate, updateEndDate);
			ResultEntity<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}
			
			// update by feily 20190323 修改json转换类库 begin
			/* 
			PermissionDataForm[] arrayMenus = JSON.decodeArray(resultContent.getBusinessObject(), PermissionDataForm.class);
			for (int i = 0; i < arrayMenus.length; i++) {
				permissions.add(arrayMenus[i]);
			}
			*/
			
			String businessObject = resultContent.getBusinessObject();
			List<PermissionDataForm> arrayMenus = JSONObject.parseArray(businessObject, PermissionDataForm.class);

			for(PermissionDataForm permissionDataForm:arrayMenus){
				permissions.add(permissionDataForm);
			}
			// update by feily 20190323 修改json转换类库 end
			
			resultEntity.setBusinessObject(permissions);

		} catch (Exception ex) {
			this.logError("获取权限信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * 增量获取角色信息列表
	 * @param requestParam
	 * @return 获取结果
	 */
	public ResultEntity<List<RoleDataForm>> queryRoles(RequestParam requestParam) {
		this.logMethodCalled("queryRoles");
		this.logParamValue("requestParam", requestParam);

		Date updateBeginDate = requestParam.getUpdateBeginDate();
		Date updateEndDate = requestParam.getUpdateEndDate();

		ResultEntity<List<RoleDataForm>> resultEntity = new ResultEntity<List<RoleDataForm>>();

		// 验证参数
		Result result = this.validateParams();
		if(!result.isSuccess()){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(result.getMessage());
			return resultEntity;
		}

		try {
			List<RoleDataForm> roles = new ArrayList<RoleDataForm>();

			String url = this.buildUrl("queryRoles", updateBeginDate, updateEndDate);
			ResultEntity<String> resultContent = requestGet(url);
			if(!resultContent.isSuccess()){
				resultEntity.setSuccess(false);
				resultEntity.setMessage(resultContent.getBusinessObject());
				return resultEntity;
			}
			
			// update by feily 20190323 修改json转换类库 begin
			/* 
			RoleDataForm[] arrayMenus = JSON.decodeArray(resultContent.getBusinessObject(), RoleDataForm.class);
			for (int i = 0; i < arrayMenus.length; i++) {
				roles.add(arrayMenus[i]);
			}
			*/
			
			String businessObject = resultContent.getBusinessObject();
			List<RoleDataForm> arrayMenus = JSONObject.parseArray(businessObject, RoleDataForm.class);

			for(RoleDataForm roleDataForm:arrayMenus){
				roles.add(roleDataForm);
			}
			// update by feily 20190323 修改json转换类库 end

			resultEntity.setBusinessObject(roles);

		} catch (Exception ex) {
			this.logError("获取角色信息异常", ex);

			resultEntity.setSuccess(false);
			resultEntity.setMessage(ex.getMessage());
		}

		return resultEntity;
	}

	/**
	 * http get 请求
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	protected ResultEntity<String> requestGet(String url) throws IOException, ClientProtocolException {
		this.logMethodCalled("requestGet");
		this.logParamValue("url", url);

		ResultEntity<String> resultEntity = new ResultEntity<String>();

		CloseableHttpClient client = HttpClientBuilder.create().build();
		CloseableHttpResponse response = client.execute(new HttpGet(url));

		String bodyAsString = EntityUtils.toString(response.getEntity());
		resultEntity.setBusinessObject(bodyAsString);
		resultEntity.setSuccess(response.getStatusLine().getStatusCode() == 200);

		return resultEntity;
	}

	/**
	 * 验证参数
	 * @return
	 */
	protected Result validateParams() {
		Result result = new Result();

		if(Strings.isEmpty(this.getAppToken())){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_APP_TOKEN_NULL);
			return result;
		}

		return result;
	}

	/**
	 * 构建请求服务路径
	 * @param serviceName
	 * @return
	 */
	protected String buildUrl(String serviceName) {
		//String url = serverPath + "/data/{0}?appToken={1}"; //v1版本uuap接口（南宁使用）
		String url = serverPath + "/data/{0}?cwAppToken={1}"; //v2版本uuap接口
		url = Strings.format(url, serviceName, appToken);
		return url;
	}

	/**
	 * 构建请求服务路径
	 * @param serviceName
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	protected String buildUrl(String serviceName, Date beginDate, Date endDate) throws UnsupportedEncodingException {

		String url = this.buildUrl(serviceName);
		url = url + "&updateBeginDate={0}&updateEndDate={1}";
		url = Strings.format(url, DateHelper.formatDate(beginDate), DateHelper.formatDate(endDate));
		return url;
	}

	public String getServerPath() {
		return serverPath;
	}

	public void setServerPath(String serverPath) {
		this.serverPath = serverPath;
	}

	public String getAppToken() {
		return appToken;
	}

	public void setAppToken(String appToken) {
		this.appToken = appToken;
	}

}
